#ifndef ASIO_THREAD_H
#define ASIO_THREAD_H

#include <iostream>
#include <cstdint>
#include <asio.hpp>

namespace T_ASIO
{
    class AsioThread {
    public:
        enum class State {
            Ready,   // 准备就绪（尚未启动）
            Running, // 正在运行
            Stopped  // 已停止
        };

        AsioThread();
        ~AsioThread();
        AsioThread(AsioThread&) = delete;
        AsioThread& operator=(const AsioThread&) = delete;
        AsioThread(AsioThread&& other) = delete;
        AsioThread& operator=(AsioThread&& other) = delete;

        // 启动线程
        bool start_thread(const std::string& name = "");
        // 发出线程停止请求
        void stop_thread();
        // 回收线程
        void join();
        // 向线程发送任务
        template <typename F>
        void post_task(F&& f)
        {
            asio::post(io_context_, std::forward<F>(f));
        }

        // 获取线程运行状态
        State get_state() const;
        // 获取线程ID
        std::thread::id get_id() const;
        // 获取线程上下文
        asio::io_context& get_io_context();
        asio::steady_timer& get_timer();


        // 获取系统时间
        uint64_t posix_time_s();
        uint64_t posix_time_ms();
        uint64_t posix_time_us();
        uint64_t posix_time_ns();

    private:
        // 线程的入口函数，负责运行io_context
        void thread_entry(const std::string& name);
        static void set_current_thread_name(const std::string& name);

        asio::io_context                                                io_context_;
        asio::executor_work_guard<asio::io_context::executor_type>      work_guard_;
        std::unique_ptr<std::thread>                                    work_thread_;
        std::atomic<State>                                              state_;
        asio::steady_timer                                              timer_;
    };
}
#endif //ASIO_THREAD_H
